package com.example.yunpicture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yunpicture.exception.ErrorCode;
import com.example.yunpicture.exception.ThrowUtils;
import com.example.yunpicture.model.dto.spaceuser.SpaceUserAddRequest;
import com.example.yunpicture.model.dto.spaceuser.SpaceUserQueryRequest;
import com.example.yunpicture.model.entity.Space;
import com.example.yunpicture.model.entity.SpaceUser;
import com.example.yunpicture.model.entity.User;
import com.example.yunpicture.model.enums.SpaceRoleEnum;

import com.example.yunpicture.model.vo.SpaceUserVO;
import com.example.yunpicture.model.vo.SpaceVO;
import com.example.yunpicture.model.vo.UserVO;
import com.example.yunpicture.service.SpaceService;
import com.example.yunpicture.service.SpaceUserService;
import com.example.yunpicture.mapper.SpaceUserMapper;
import com.example.yunpicture.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author LenoVO
 * @description 针对表【space_user(空间用户关联)】的数据库操作Service实现
 * @createDate 2025-04-06 10:34:05
 */
@Service
public class SpaceUserServiceImpl extends ServiceImpl<SpaceUserMapper, SpaceUser>
        implements SpaceUserService {

    @Resource
    private SpaceService spaceService;

    @Resource
    private UserService userService;
    /**
     * 添加空间成员
     *
     * @param userAddRequest
     * @return
     */
    public long addSpaceUser(SpaceUserAddRequest userAddRequest) {
        //校验参数
        ThrowUtils.throwif(userAddRequest==null,ErrorCode.PARAMS_ERROR);
        SpaceUser spaceUser = new SpaceUser();
        BeanUtils.copyProperties(userAddRequest,spaceUser);
        validSpaceUser(spaceUser,true);
        //操作数据库
        boolean result = this.save(spaceUser);
        ThrowUtils.throwif(!result,ErrorCode.OPERATION_ERROR);
        return spaceUser.getId();
    }


    /**
     * 查询条件
     *
     * @param spaceUserQueryRequest
     * @return
     */
    public QueryWrapper<SpaceUser> getQueryWrapper(SpaceUserQueryRequest spaceUserQueryRequest) {
        QueryWrapper<SpaceUser> queryWrapper = new QueryWrapper<>();
        if (spaceUserQueryRequest==null){
            return queryWrapper;
        }
        Long id = spaceUserQueryRequest.getId();
        Long userId = spaceUserQueryRequest.getUserId();
        Long spaceId = spaceUserQueryRequest.getSpaceId();
        String spaceRole = spaceUserQueryRequest.getSpaceRole();
        queryWrapper.eq(ObjectUtil.isNotEmpty(id),"id",id);
        queryWrapper.eq(ObjectUtil.isNotEmpty(userId),"user_id",userId);
        queryWrapper.eq(ObjectUtil.isNotEmpty(spaceId),"space_id",spaceId);
        queryWrapper.eq(ObjectUtil.isNotEmpty(spaceRole),"space_role",spaceRole);
        return queryWrapper;
    }

    /**
     * 查询单个封装类
     *
     * @param spaceUser
     * @return
     */
    public SpaceUserVO getSpaceUserVO(SpaceUser spaceUser) {
        SpaceUserVO spaceUserVO = SpaceUserVO.objToVo(spaceUser);
        Long userId = spaceUserVO.getUserId();
        if (userId!=null&&userId>0){
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            spaceUserVO.setUser(userVO);
        }
        Long spaceId = spaceUserVO.getSpaceId();
        if (spaceId!=null&&spaceId>0){
            Space space = spaceService.getById(spaceId);
            SpaceVO spaceVO = spaceService.getSpaceVO(space);
            spaceUserVO.setSpace(spaceVO);
        }
        return spaceUserVO;
    }

    /**
     * 查询单个封装类
     *
     * @param spaceUserList
     * @return
     */
    public List<SpaceUserVO> getSpaceUserVOList(List<SpaceUser> spaceUserList) {
        if (CollUtil.isEmpty(spaceUserList)) {
            return Collections.emptyList();
        }
        //将实体类列表转成封装类列表
        List<SpaceUserVO> spaceUserVOList = spaceUserList.stream().map(SpaceUserVO::objToVo).collect(Collectors.toList());
        //收集用户id列表和空间id
        Set<Long> userIdSet = spaceUserList.stream().map(SpaceUser::getUserId).collect(Collectors.toSet());
        Set<Long> spaceIdSet = spaceUserList.stream().map(SpaceUser::getSpaceId).collect(Collectors.toSet());
        //批量查询user和space
        Map<Long, List<User>> userListMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        Map<Long, List<Space>> spaceListMap = spaceService.listByIds(spaceIdSet).stream().collect(Collectors.groupingBy(Space::getId));
        //填充VO中的user和space
        spaceUserVOList.forEach(spaceUserVO -> {
            Long userId = spaceUserVO.getUserId();
            Long spaceId = spaceUserVO.getSpaceId();
            // 填充用户信息
            User user = null;
            if (userListMap.containsKey(userId)) {
                user = userListMap.get(userId).get(0);
            }
            spaceUserVO.setUser(userService.getUserVO(user));
            // 填充空间信息
            Space space = null;
            if (spaceListMap.containsKey(spaceId)) {
                space = spaceListMap.get(spaceId).get(0);
            }
            spaceUserVO.setSpace(SpaceVO.objToVo(space));
        });
        return spaceUserVOList;
    }

    /**
     * 校验空间成员对象
     *
     * @param spaceUser
     * @param add
     */
    public void validSpaceUser(SpaceUser spaceUser, boolean add) {
        ThrowUtils.throwif(spaceUser == null, ErrorCode.PARAMS_ERROR);
        Long userId = spaceUser.getUserId();
        Long spaceId = spaceUser.getSpaceId();
        if (add) {
            //新建空间
            ThrowUtils.throwif(userId == null || spaceId == null,ErrorCode.PARAMS_ERROR);
            User user = userService.getById(userId);
            ThrowUtils.throwif(user==null,ErrorCode.PARAMS_ERROR,"用户不存在");
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwif(space==null,ErrorCode.PARAMS_ERROR,"空间不存在");
        }
        //校验空间角色
        String spaceRole = spaceUser.getSpaceRole();
        SpaceRoleEnum enumByValue = SpaceRoleEnum.getEnumByValue(spaceRole);
        ThrowUtils.throwif(spaceRole!=null&&enumByValue==null,ErrorCode.PARAMS_ERROR,"空间角色不存在");
    }
}




